package com.example.ssmlab1.controller;

import com.example.ssmlab1.DB;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
@RequestMapping("user")
public class UserController extends BaseController{
    @RequestMapping("sign_in")
    private String signIn(){
        System.out.println("登录");
        int id = Integer.parseInt(request.getParameter("id"));
        String password = request.getParameter("password");
        Connection connection = DB.getConnection();
        String sql = "SELECT * from db_user.user where id= ? and password = ?";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,id);
            preparedStatement.setString(2,password);
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                request.getSession().setAttribute("username",resultSet.getString("username"));
                return "redirect:/home.jsp";
            }else {
                request.setAttribute("message","ID 或 密码有误请重新输入！");
                return "forward:/index.jsp";
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DB.closeSqlConnect(connection,preparedStatement,resultSet);
        }

    }
    @RequestMapping("sign_up")
    private String signUp(){
        System.out.println("注册");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Connection connection = DB.getConnection();
        String sql = "INSERT INTO db_user.user(username, password) values (?,?)";
        String sqlSelectId = "select last_insert_id()";
        PreparedStatement preparedStatement=null;
//        PreparedStatement preparedStatementSelectId =null;
        ResultSet resultSet = null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            preparedStatement.executeUpdate();

            preparedStatement = connection.prepareStatement(sqlSelectId);
            resultSet = preparedStatement.executeQuery();
            resultSet.next();
            int id = resultSet.getInt(1);
            request.setAttribute("message","注册成功！你的ID是："+id);
            return "forward:/index.jsp";
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DB.closeSqlConnect(connection,preparedStatement,resultSet);
        }
    }
}
